package com.misty.api.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author: HuangJun
 * @email: huangjun@1fda.com
 * @date: 2022/10/20 16:21
 * @description: 解析Excel类
 */
@Slf4j
public class BlogExcelListener<T> extends AnalysisEventListener<T> {
    //每次读取100条数据就进行保存操作
    private static final int BATCH_COUNT = 100;
    List<T> list = new ArrayList<>();

    private final Consumer<List<T>> consumer;

    public BlogExcelListener(Consumer<List<T>> consumer) {
        this.consumer = consumer;
    }

    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            consumer.accept(list);
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        consumer.accept(list);
    }
}
